package net.xumf.web.controller.common;

import net.xumf.support.common.BaseService;
import net.xumf.support.converter.Converter;
import net.xumf.support.enums.CodeEnum;
import net.xumf.support.model.ResponseResult;
import net.xumf.support.model.dto.PageDTO;
import net.xumf.support.model.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * 通用Controller
 *
 * @param <T>  用于拓展分页对象
 * @param <S>  {@link BaseService} jpa增删改查的接口
 * @param <P>  pojo 对象
 * @param <ID> 对应表中的主键类型
 */
public abstract class BaseControllerImpl<T extends PageDTO, S extends BaseService<P, ID>, P, ID> implements BaseController<T, P, ID> {

    @Autowired
    protected S service;

    @Override
    public ResponseResult get(@PathVariable ID id) {
        return service.getById(id).map(ResponseResult::success).orElseGet(ResponseResult::failure);
    }

    @Override
    public ResponseResult add(@RequestBody P p) {
        service.add(p);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult edit(@PathVariable ID id, @RequestBody P p) {
        return service.getById(id).map(o -> {
            Converter.to(o, p, true);
            service.update(o);
            return ResponseResult.success(CodeEnum.MODIFY_SUCCESS);
        }).orElse(ResponseResult.failure(CodeEnum.MODIFY_NOT_FOUND_ROW_ERROR));
    }

    @Override
    public ResponseResult del(@PathVariable ID id) {
        return service.getById(id).map(o -> {
            service.remove(id);
            return ResponseResult.success(CodeEnum.DELETE_SUCCESS);
        }).orElse(ResponseResult.failure(CodeEnum.DELETE_NOT_FOUND_ROW_ERROR));
    }

    @Override
    public ResponseResult delAll() {
        service.removeAll();
        return ResponseResult.success();
    }

    @Override
    public PageVO getByPage(T pageDTO) {
        return service.getByPage(pageDTO);
    }

    @Override
    public ResponseResult getAll() {
        return ResponseResult.success(service.getAll());
    }
}
